package ahblue.cn.tanzi.ui;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.Toast;

import java.util.ArrayList;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.TanZiApplication;
import ahblue.cn.tanzi.cache.ACache;
import ahblue.cn.tanzi.jmessage.JMessageManage;
import ahblue.cn.tanzi.jmessage.im.base.BaseActivity;
import ahblue.cn.tanzi.jmessage.im.database.UserEntry;
import ahblue.cn.tanzi.jmessage.im.ui.FriendRecommendActivity;
import ahblue.cn.tanzi.jmessage.im.ui.fragment.ContactsFragment;
import ahblue.cn.tanzi.jmessage.im.ui.fragment.ConversationListFragment;
import ahblue.cn.tanzi.jpush.ExampleUtil;
import ahblue.cn.tanzi.jpush.LocalBroadcastManager;
import ahblue.cn.tanzi.jpush.PushModel;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.model.user.UserModel;
import ahblue.cn.tanzi.ui.circle.CircleFragment;
import ahblue.cn.tanzi.ui.home.HomeFragment;
import ahblue.cn.tanzi.ui.person.LoginActivity;
import ahblue.cn.tanzi.ui.person.PersonFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import pub.devrel.easypermissions.EasyPermissions;

//https://www.jianshu.com/p/97fa1d9160de?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

public class MainActivity extends BaseActivity {

    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    @BindView(R.id.frameLayout_fragment)
    FrameLayout mFrameLayoutContainer;
    @BindView(R.id.navigation)
    BottomNavigationView mNavigation;

    public static boolean isForeground = false;

    private HomeFragment mHomeFragment;
    private CircleFragment mCircleFragment;
    private PersonFragment mPersonFragment;
    private ConversationListFragment mMsgFragment1;

    private MessageReceiver mMessageReceiver;
    private boolean bind=false;

    private ArrayList<Fragment> fragments ;
    private static final String[] TAGS = {"home","circle","msg","mine"};
    private int prePos;
    private String PRE = "PREPOS";

    private static final String[] READ_WRITE_EXTERNAL_STORAGE =
            {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private static final int RC_RW_STORAGE_PERM = 123;


    // 极光
    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        //注册sdk的event用于接收各种event事件
        JMessageClient.registerEventReceiver(this);
        setRelogin(new relogIn() {
            @Override
            public void switchHome() {
                switchFragment(0);
            }
        });
        init();
        registerMessageReceiver();  // used for receive msg
        mNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        if(savedInstanceState==null){
            //默认为0
            prePos = 0;
            fragments = new ArrayList<>(3);
            buildFragmentList();
        }else{
            //内存被回收了，fragments的list也被回收了，重新add进去
            prePos = savedInstanceState.getInt(PRE);
            fragments = new ArrayList<>(3);
            HomeFragment homeFragment = (HomeFragment) getSupportFragmentManager().findFragmentByTag(TAGS[0]);
            CircleFragment circleFragment = (CircleFragment) getSupportFragmentManager().findFragmentByTag(TAGS[1]);
            ConversationListFragment msgFragment = (ConversationListFragment) getSupportFragmentManager().findFragmentByTag(TAGS[2]);
            PersonFragment mineFragment = (PersonFragment) getSupportFragmentManager().findFragmentByTag(TAGS[3]);
            fragments.add(homeFragment);
            fragments.add(circleFragment);
            fragments.add(msgFragment );
            fragments.add(mineFragment);
        }

        //设置默认
        setDefaultFragment(prePos);

        // 检车是否有用户登录
        if (LoginResultModel.checkUserInfoExist(this)) {
            if (!JMessageManage.checkLogin()) {
                UserModel model = LoginResultModel.getUserAllModel(this, UserModel.class);
                if (null == model) {
                    UserModel.getUserInfo(this, LoginResultModel.getToken(this), new UserModel.UserInfoLoginStatus() {
                        @Override
                        public void conver(UserModel model) {
                            if (model != null) {
                                JMessageManage.login(model.invite_code, model.pass_word);
                            } else {
                                JMessageManage.quit();
                                ACache.get(MainActivity.this).clear();
                                LoginActivity.into(MainActivity.this);
                                switchHome();
                            }

                        }
                    });
                } else {
                    JMessageManage.login(model.invite_code, model.pass_word);
                }

            }
        } else {
            LoginActivity.into(this);
            finish();
        }

//        String udid =  ExampleUtil.getImei(getApplicationContext(), "");
//        String appKey = ExampleUtil.getAppKey(getApplicationContext());

//        String packageName =  getPackageName();
//        String deviceId = ExampleUtil.getDeviceId(getApplicationContext());
//        String versionName =  ExampleUtil.GetVersion(getApplicationContext());
        //  JPushInterface.stopPush(getApplicationContext());
        //   JPushInterface.resumePush(getApplicationContext());

        if (LoginResultModel.checkUserInfoExist(this) && !bind){
            String RegId = JPushInterface.getRegistrationID(getApplicationContext());
            bindRegid(RegId);
            bind=true;
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void bindRegid(String regId) {
        PushModel.Bind(this,regId);
    }


    // 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
    private void init(){
        JPushInterface.init(getApplicationContext());

        EasyPermissions.requestPermissions(
                this,
                getString(R.string.need_storge_permission),
                RC_RW_STORAGE_PERM,
                READ_WRITE_EXTERNAL_STORAGE);
    }

    public void switchHome() {
        switchFragment(0);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null!=mPersonFragment)
        mPersonFragment.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            // 利用handler延迟发送更改状态信息
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    // 定义一个变量，来标识是否退出
    private static boolean isExit = false;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
        if (LoginResultModel.checkUserInfoExist(this)  && !bind ){
            String RegId = JPushInterface.getRegistrationID(getApplicationContext());
            bindRegid(RegId);
            bind=true;
        }
    }


    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    private void setCostomMsg(String msg) {
        if (!TextUtils.isEmpty(msg))
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(this, "null croadmsg", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        JMessageManage.quit();
        ACache.get(this).clear();
        super.onDestroy();
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    switchFragment(0);
                    return true;

                case R.id.navigation_quanzi:
                    switchFragment(1);
                    return true;

                case R.id.navigation_msg:
                    if (LoginResultModel.checkUserInfoExist(MainActivity.this)) {
                        switchFragment(2);
                    } else {
                        LoginActivity.into(MainActivity.this);
                    }
                    return true;

                case R.id.navigation_person:
                    // 检车是否有用户登录
                    if (LoginResultModel.checkUserInfoExist(MainActivity.this)) {
                        switchFragment(3);
                    } else {
                        LoginActivity.into(MainActivity.this);
                    }

                    return true;
            }
            return false;
        }
    };

    //设置默认
    private void setDefaultFragment(int pos){
        Fragment now = fragments.get(pos);
        if(!now.isAdded()){
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.frameLayout_fragment,fragments.get(prePos),TAGS[pos])
                    .commit();
        }else{
            getSupportFragmentManager()
                    .beginTransaction()
                    .show(now)
                    .commit();
        }
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //保存上一个位置
        outState.putInt(PRE,prePos);
    }


    private void buildFragmentList() {
        mHomeFragment = new HomeFragment();
        mCircleFragment = new CircleFragment();
        mMsgFragment1 = new ConversationListFragment();
        mPersonFragment = new PersonFragment();
        fragments.add(mHomeFragment);
        fragments.add(mCircleFragment);
        fragments.add(mMsgFragment1);
        fragments.add(mPersonFragment);
    }


    private void switchFragment(int pos) {
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        Fragment from = fragments.get(prePos);
        Fragment to = fragments.get(pos);
        if(!to.isAdded()){
            transaction.hide(from)
                    .add(R.id.frameLayout_fragment,fragments.get(pos),TAGS[pos])
                    .commit();
        }else{
            transaction.hide(from)
                    .show(to)
                    .commit();
        }
        prePos = pos;
    }

    //接收到好友事件
    public void onEvent(ContactNotifyEvent event) {
        final UserEntry user = TanZiApplication.getUserEntry();
        final String reason = event.getReason();
        final String username = event.getFromUsername();
        final String appKey = event.getfromUserAppKey();
        if (event.getType() == ContactNotifyEvent.Type.invite_received){
            showNotifiCation(TanZiApplication.mAppContext,username);
        }

        ContactsFragment jdFragment = new ContactsFragment();
        jdFragment.onEvent(event);
    }

    /**
     * 通知消息
     *  @param activity
     * @param
     */
    public void showNotifiCation(Context activity,String username) {
        String id = "my_channel_01";
        String name="baidu";
        NotificationManager notificationManager = (NotificationManager) activity.getSystemService(NOTIFICATION_SERVICE);
        Notification notification = null;
        Intent notificationIntent = new Intent(this, FriendRecommendActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
//			Toast.makeText(activity, mChannel.toString(), Toast.LENGTH_SHORT).show();
            notificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(activity)
                    .setChannelId(id)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                    .setContentTitle("添加好友提醒")
                    .setContentText(username+"请求添加你为好友")
                    .setSmallIcon(R.mipmap.ic_launcher).build();
        } else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(activity)
                    .setContentTitle("添加好友提醒")
                    .setContentText(username+"请求添加你为好友")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                    .setOngoing(true);
//					.setChannel(id);//无效
            notification = notificationBuilder.build();
        }
        notificationManager.notify(111123, notification);
    }
}
